package com.yanqu.road.server.manager.activity.biaoju;

import com.yanqu.road.entity.union.activitygroup.UnionActivityGroup;
import com.yanqu.road.logic.helper.UnionActivityGroupHelper;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CrossBiaoJuGroup {
    private int activityId;
    private Map<Integer, CrossBiaoJuActivity> activityMap = new ConcurrentHashMap<>();

    public CrossBiaoJuGroup(int activityId) {
        this.activityId = activityId;
    }

    public int getActivityId() {
        return activityId;
    }

    public Map<Integer, CrossBiaoJuActivity> getActivityMap() {
        return activityMap;
    }

    public CrossBiaoJuActivity getActivity(int unionGroup) {
        if (unionGroup == UnionActivityGroupHelper.NO_GROUP_ID) {
            return null;
        }
        CrossBiaoJuActivity activity = activityMap.get(unionGroup);
        if (activity == null) {
            synchronized (activityMap) {
                activity = activityMap.get(unionGroup);
                if (activity == null) {
                    activity = new CrossBiaoJuActivity(unionGroup, activityId);
                    activityMap.put(unionGroup, activity);
                }
            }
        }
        return activity;
    }

    public void runTask() {
        for (CrossBiaoJuActivity activity : activityMap.values()) {
            try {
                activity.roundChangeTask();
                activity.runEscortTask();
            } catch (Exception e) {
                CrossBiaoJuMgr.getLogger().error("CrossBiaoJuGroup runTask error activityId:{} group:{} err:{}", activity.getActivityId(), activity.getUnionGroup(), e);
            }
        }

    }

    public void rankSortTask() {
        for (CrossBiaoJuActivity activity : activityMap.values()) {
            try {
                activity.rankSortTask();
            } catch (Exception e) {
                CrossBiaoJuMgr.getLogger().error("CrossBiaoJuGroup rankSortTask error activityId:{} group:{} err:{}", activity.getActivityId(), activity.getUnionGroup(), e);
            }
        }
    }

    public void save() {
        for (CrossBiaoJuActivity activity : activityMap.values()) {
            try {
                activity.save();
            } catch (Exception e) {
                CrossBiaoJuMgr.getLogger().error("CrossBiaoJuGroup save error activityId:{} group:{} err:{}", activity.getActivityId(), activity.getUnionGroup(), e);
            }
        }
    }
}
